import requests
import bs4
import os
import re
import sys
import time

urlHome = 'http://poj.org'
urlLogin = 'http://poj.org/login'
urlSubmit = 'http://poj.org/submit'
urlStatus = 'http://poj.org/status'
dictLanguage = {
	'G++':'0', 'GCC':'1', 'JAVA':'2', 
	'PASCAL':'3', 'C++':'4', 'C':'5',
	'FORTRAN':'6' }
listStatus = [
	'Run ID', 'User', 'Problem', 'Result',
	'Memory', 'Time', 'Language', 'Code Length',
	'Submit Time' ]
dictError = { 
	0:u'get page error', -1:u'Waiting', 
	-2:u'Compiling', -3:u'Running & Judging' }


	
def get_results(session, statusData):
	try:
		response = session.get(urlStatus, params=statusData)
		page = response.content
	except:
		return 0, None
	
	try:
		bs = bs4.BeautifulSoup(page)
		table = bs.html.body.find('table', cellspacing='0')
		tr = table.find('tr', align='center')
		results = list(tr.strings)
		for key in dictError:
			if dictError[key] == results[3]:
				return key, None
		else:
			print page
			return 1, results
	except:
	  	return 0, None


def get_status(user_id):
	session = requests.session()
	statusData = { 'user_id':user_id }
	for ith in range(5):
		res, results = get_results(session, statusData)
		print results
		if res <= 0: 
			time.sleep(1)
		else:
			parser_result = "%d|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|" \
			% (0, "Success", results[0], results[8], results[1], \
			results[2], results[3], results[6], results[5], \
			results[4],results[7])	
			return parser_result
	
	parser_result = "%d|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|" \
	%  (1, "Parse Error", "#", "#", "#", "#", "#", "#", "#", "#", "#")	
	return parser_result

if __name__ == '__main__':
	get_status("gvj0")
